package threadLock.otherBasice;

import java.util.ArrayList;

/**
 * 线程并发不大的 使用volatile 在一定程度上可以保证线程的安全性
 */
public class VolatileTest {

    private static volatile ArrayList<User> users = new ArrayList<>();

    public static void main(String[] args) {
        Thread threadOne = new Thread(() -> {
            User user = new User();
            user.setAge("19");
            user.setName("小红");
            users.add(user);
        }, "threadOne");

        Thread threadTwo = new Thread(() -> {
            User user = new User();
            user.setAge("21");
            user.setName("小黄");
            users.add(user);
        }, "threadTwo");

        User user = new User();
        user.setAge("20");
        user.setName("小紫");
        users.add(user);
        threadOne.start();
        threadTwo.start();
        users.forEach(item -> {
            System.out.println(item.getAge());
            System.out.println(item.getName());
        });
    }

}

class User {
    private volatile String name;

    private volatile String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}
